<?php
/*
$base = new Imagick('orig.jpg');
$mask = new Imagick('mask.png');
$over = new Imagick('over.png');

// Setting same size for all images
$base->resizeImage(274, 275, Imagick::FILTER_LANCZOS, 1);

// Copy opacity mask
//$base->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0, Imagick::CHANNEL_ALPHA);

// Add overlay
//$base->compositeImage($over, Imagick::COMPOSITE_DEFAULT, 0, 0);

//$base->compositeImage($over, Imagick::CONVERT, 32, 32)

$base->writeImage('output.png');


$path = 'images/';

// Create new objects from png's
$dude = new Imagick($path . 'dude.png');
$mask = new Imagick($path . 'dudemask.png');

// IMPORTANT! Must activate the opacity channel
// See: http://www.php.net/manual/en/function.imagick-setimagematte.php
$dude->setImageMatte(1); 

// Create composite of two images using DSTIN
// See: http://www.imagemagick.org/Usage/compose/#dstin
$dude->compositeImage($mask, Imagick::COMPOSITE_DSTIN, 0, 0);

// Write image to a file.
$dude->writeImage($path . 'newimage.png');

header("Content-Type: image/png");

echo $base;

//echo $dude;

*/
?>

<?php
session_start();
include 'includes/inc_cartfuncs.php';
include 'includes/inc_imagefuncts.php';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script type="text/javascript" defer="defer" src="/js/jquery-1.6.4.js"></script>
  <script type="text/JavaScript" defer="defer" src="/js/jquery.cycle.js"></script>
</head>

<body>

  <div id="wrapper">
    <?php
        $containerx=400;  // x of samples
        $containery=300;  // y of samples
        $number=92;       // no of samples
        $master=0;

        while($master==0) {  // always
          $factors = getFactors($number); // factors of number of images
          echo "factors for ".$number." ";
          print_r($factors);
          echo "<br />";
          $c = count($factors);   // count of factors
          if(($c%2)==1) {           // loop through $number, decreasing each time if below loop is not satisfied
            while ($factors%2==1) {
              $number--;
              $factors = getFactors($number);
              $c = count($factors);
            }
          }

          $q=0;
          $half_factors = count($factors)/2;
          for($i=0;$i<$half_factors;$i++) {   // for each factor of number
            $f = $factors[$i];    // get first factor (+1 in loop)

            $count = ($c-1)-$q;   // last factor (-1 in loop)

            $f_end = $factors[$count];  // get last factor (-1 in loop)

            if(($f*$f_end)==$number) {    // if factors multiply to give $number (always should)
              if(($f_end-$f)<=(floor($number/50))) {    // if high factor - low factor = rounded down $number / 50
                $a = $f;
                $b = $f_end;
                $master=1;    // break master loop
              }
            }
            $q++; // $q is the value used to decrement high factor
          }
          if($master==0)  // if solution is not found, decrease $number by one and re-start
            $number--;
          else {    // else solution
            echo "SAMPLE IMAGES X = ".$a."<br />";
            echo "SAMPLE IMAGES Y = ".$b,"<br /><br /><br />";
          }
          if ($c==0) {  // error to avoid infinite loop
            echo "ERROR: fail";
            break;
          }
        }

        $x = floor($containerx/$a);
        $y = floor($containery/$b);

        // loop though each file
        $v=0;
        $num_samples=0;
        $gm=999999999;

        $directory= "images/test/";
        $files1 = scandir($directory);
        //$dir = '/tmp';
        $dh  = opendir($directory);
        while (false !== ($filename = readdir($dh))) {
            $ext = substr($filename, strrpos($filename, '.') + 1);
            if(in_array($ext, array("jpg","jpeg","png","gif")))
                $filenames[] = $filename;
        }
        // TODO supply your own filenames
        //$filenames = $files1;

        foreach ($filenames as $filename) {
          $v++;
          $luminance = get_avg_luminance($filename,count($filenames),$x,$y,$gm,$a,$b);
          $gm=$luminance;
          //echo "AVERAGE LUMINANCE = $luminance<br />";

          // assume a medium gray is the threshold, #acacac or RGB(172, 172, 172)
          // this equates to a luminance of 170
          if ($luminance < 50)
            echo '1<br />';
          elseif ($luminance < 100)
            echo "2<br />";
          elseif ($luminance < 150)
            echo '3<br />';
          elseif ($luminance < 200)
            echo '4<br />';
          elseif ($luminance < 250)
            echo '5<br />';
          elseif ($luminance < 300)
            echo '6<br />';
          elseif ($luminance < 350)
            echo '7<br />';
            echo "<br />";
        }
                  if (($filename != '.') && ($filename != '..')) {
        echo imageshow("images/new");}
      exit;


    


    

      if(glob($directory . "*.jpg") != false) {
        $filecount = count(glob($directory . "*.jpg"));
        echo $filecount;
      }
      else
        echo 0;


    function imageshow($dir) {
      echo "TOTAL = ".count($files1);
      $files = scandir($dir);
      $returnval='';
      $q=0;
      foreach($files as $file) {
        $count[$q] = $file;
        $q++;
        //echo "q = ".$q."<br />";
      }
      sort($count, SORT_NUMERIC);
      for($a=0;$a<count($count);$a++) {
        $returnval.='<img width=50 height=50 src=\'images/new/'.$count[$a].'\' />'; 

        $how_many=0;
        list($colors_key, $colors) = get_avg_colour($a, $count);
        for ($i = 0; $i <= $how_many; $i++)
        {
          $returnval.="<span style='background:#".$colors_key[$i].";width=50px;height=50px;' >".$colors[$colors_key[$i]]."</span>";
        }
      }
      return $returnval;
    }

    function get_avg_colour($a,$count) {
      if (($a!=0)&&($a!=1)) {
        include_once("colors.inc.php");
        $ex=new GetMostCommonColors();
        //echo "COUNT = ".$count;
        //echo "<br />A = ".$a."<br />";
        //echo "TOTAL = ".$count[$a];
        $ex->image='images/new/'.$count[$a];
        $colors=$ex->Get_Color();
        $how_many=0;
        $colors_key=array_keys($colors);

        return array($colors_key,$colors);
      }
      else
        return false;
    }

    function toRGB($Hex){
      if (substr($Hex,0,1) == "#")
      $Hex = substr($Hex,1);

      $R = substr($Hex,0,2);
      $G = substr($Hex,2,2);
      $B = substr($Hex,4,2);

      $R = hexdec($R);
      $G = hexdec($G);
      $B = hexdec($B);

      $RGB['R'] = $R;
      $RGB['G'] = $G;
      $RGB['B'] = $B;

      return $RGB;
    }



    // get average luminance, by sampling $num_samples times in both x,y directions
    function get_avg_luminance($filename, $num_samples=10,$width,$height,$grandmaster,$a_axis,$b_axis) {
      $image = "images/test/".$filename;
      $new = "images/new/".$filename;
      $num_samples=0;
      //echo "IMAGE = ".$image."<br />";
      $num_samples++;

      @copy($image, $new);
      //echo "NEW IMAGE = ".$new."<br />";

      if ($filename != '.') {
        echo "<br/ >Filename = ".$filename."   ";
        include("colors.inc.php");
        $ex=new GetMostCommonColors();
        $ex->image='images/test/'.$filename;
        $colors=$ex->Get_Color();
        $colors_key=array_keys($colors);

        echo "<span style=\"background:#".$colors_key[0]."\">COLOUR!</span>    ";

        // *** Include the class
        // *** 1) Initialize / load image
        $resizeObj = new resize('images/test/hero.jpg');
        // *** 2) Resize image (options: exact, portrait, landscape, auto, crop)
        $resizeObj -> resizeImage($a_axis, $b_axis, 'exact');
        // *** 3) Save image
        $resizeObj -> saveImage('sample.png', 100);

        $im = imagecreatefrompng("sample.png");

        echo "a = ".$a_axis." and b = ".$b_axis."<br />";
        for($x=0;$x<$a_axis;$x++) {
          for($y=0;$y<$b_axis;$y++) {
            $rgb2 = imagecolorat($im, $x, $y);
            echo "currently on pixel: ".$x, $y."<br />";
            $r = ($rgb2 >> 16) & 0xFF;
            $g = ($rgb2 >> 8) & 0xFF;
            $b = $rgb2 & 0xFF;
            $RGB = toRGB($colors_key[0]);
            $col = (pow((30*($r-$RGB['R'])),2)) + (pow((59*($g-$RGB['G'])),2)) + (pow((11*($b-$RGB['B'])),2));

            if ($col<$grandmaster)  {
              $grandmaster=$col;
              echo "<span style=\"background:#".$colors_key[0]."\">THIS PIXEL IS </span>    <span style=\"background:#".rgb2html($rgb2)."\">THIS </span>    ";
              echo "<strong>Replaced BEST FIT with: ".$filename."</strong><br />";
            }
          }
        }

        /*$rgb = imagecolorat($im, 0, 2);
        echo "Test pixel colour = ".$rgb."   ";
        $r = ($rgb >> 16) & 0xFF;
        $g = ($rgb >> 8) & 0xFF;
        $b = $rgb & 0xFF;

        $RGB = toRGB($colors_key[0]);*/

        //d2 = (30*(r1-r2))**2 + (59*(g1-g2))**2 + (11*(b1-b2))**2;
        //$col = (pow((30*($r-$RGB['R'])),2)) + (pow((59*($g-$RGB['G'])),2)) + (pow((11*($b-$RGB['B'])),2));
        /*if ($col<$grandmaster)  {
          $grandmaster=$col;
          echo "<strong>Replaced BEST FIT with: ".$filename."</strong><br />";
        }*/

        $width=100; //*** Fix Width & Heigh (Autu caculate) ***//
        $height=100;
        
        $img = imagecreatefromjpeg("images/test/".$filename);
        

        /*$x_step = intval($width/$num_samples);
        $y_step = intval($height/$num_samples);

        $total_lum = 0;

        $sample_no = 1;

        for ($x=0; $x<$width; $x+=$x_step) {
            for ($y=0; $y<$height; $y+=$y_step) {

                $rgb = imagecolorat($img, $x, $y);
                $r = ($rgb >> 16) & 0xFF;
                $g = ($rgb >> 8) & 0xFF;
                $b = $rgb & 0xFF;

                // choose a simple luminance formula from here
                // http://stackoverflow.com/questions/596216/formula-to-determine-brightness-of-rgb-color
                $lum = ($r+$r+$b+$g+$g+$g)/6;

                $total_lum += $lum;

                // debugging code
                // echo "$sample_no - XY: $x,$y = $r, $g, $b = $lum<br />";
                $sample_no++;
            }
        }
        // work out the average
        $avg_lum  = $total_lum/$sample_no;
        $extra='';
        $r=0;
        while (file_exists("images/new/".round($avg_lum,2).$extra.".jpg")) {
          $r++;
          $extra=$r;
        }
        rename($new, "images/new/".round($avg_lum,2).$extra.".jpg");*/
        //return $avg_lum;
      }
      return $grandmaster;
    }

    function rgb2html($r, $g=-1, $b=-1)
{
    if (is_array($r) && sizeof($r) == 3)
        list($r, $g, $b) = $r;

    $r = intval($r); $g = intval($g);
    $b = intval($b);

    $r = dechex($r<0?0:($r>255?255:$r));
    $g = dechex($g<0?0:($g>255?255:$g));
    $b = dechex($b<0?0:($b>255?255:$b));

    $color = (strlen($r) < 2?'0':'').$r;
    $color .= (strlen($g) < 2?'0':'').$g;
    $color .= (strlen($b) < 2?'0':'').$b;
    return '#'.$color;
}


    ?>

    <img src="output.jpg">
  </div>
</body>
</html>
